const getcopyrights = async() => {
    try {
        let response = await ajax('getcopyrights?pagenum=1&pagesize=10')
        let copys = response.data,
            copyright_select = document.querySelector('.copyright')
        for (const copy of copys) {
            let option = document.createElement('option')
            option.innerHTML = copy.copyright_name
            option.value = copy.id
            copyright_select.add(option)
        }
    } catch (error) {
        alert(error.msg)
    }
}

const getgametypes = async() => {
    try {
        let response = await ajax('getgametypes?pagenum=1&pagesize=10')
        let types = response.data
        type_select = document.querySelector('.gametype')
        for (const type of types) {
            let option = document.createElement('option')
            option.innerHTML = type.typename
            option.value = type.id
            type_select.add(option)
        }
        console.log(types);
    } catch (error) {
        alert(error.msg)
    }
}

const game_add = async() => {
    let gamename = document.querySelector('.gamename').value,
        cover = document.querySelector('.cover').value,
        publishdate = document.querySelector('.publishdate').value,
        descriotion = document.querySelector('.description').value,
        system_radios = document.querySelectorAll('.system'),
        system,
        copyright_select = document.querySelector('.copyright'),
        copyright = copyright_select.options[copyright_select.selectedIndex].value
    type_select = document.querySelector('.gametype'),
        type = type_select.options[type_select.selectedIndex].value
    for (const raido of system_radios) {
        if (raido.checked) {
            system = raido.value
        }
    }
    if (!gamename || gamename.trim().length == 0) return alert('游戏名必填')
    if (!copyright) return alert('游戏公司必选')
    if (!type) return alert('游戏类型必选')
    try {
        let obj = {
            gamename,
            cover,
            publishdate,
            descriotion,
            system,
            copyright,
            type
        }
        const response = await ajax('addgame', 'POST', obj)
        console.log(response);
        console.log('添加成功');
        location.href = './games.html'
    } catch (error) {
        alert(error.meta.msg)
    }
}

window.onload = async function() {
    getcopyrights()
    getgametypes()
}